package com.ht.callback.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.bean.AjaxResult;
import com.ht.cdc.CdcConfig;
import com.ht.cdc.CdcHelper;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * CDC通知
 * @author asq
 * @createTime 2024年12月18日 20:32:08
 */
@RestController
@RequestMapping("/cdc")
@Slf4j
public class CdcController {
	@Autowired
	private CdcHelper cdcHelper;
	
	@PostMapping("/start/{appid}")
	public AjaxResult start(@PathVariable String appid) {
		// 获取open_app
		Entity openApp = Db.createSqlParser("open_app").findById(appid);
		if (openApp == null) {
			return AjaxResult.error("open_app不存在，id：" + appid);
		}
		String configStr = openApp.getStr("config");
		if (StrUtil.isBlank(configStr)) {
			return AjaxResult.error("open_app的cdc未正确配置，无法启动，id：" + appid);
		}
		JSONObject appConfig = JSONUtil.parseObj(configStr);
		
		// 获取cdc
		JSONObject config = appConfig.getJSONObject("cdc_config");
		if (config == null) {
			return AjaxResult.error("open_app的cdc未正确配置，无法启动，id：" + appid);
		}
		
		// 获取配置
		CdcConfig cdcConfig = CdcConfig.create(config);
		long tenantId = openApp.getLong("tenant_id");
		String name = openApp.getStr("name");
		
		// 启动
		try {
			cdcHelper.start(cdcConfig, tenantId, appid);
			log.info("[cdc]启动任务成功，租户ID：{}，cdc名称：{}", tenantId, name);
		} catch (Exception e) {
            log.error("[cdc]启动任务失败: {}", e.getMessage(), e);
		}
		
		return AjaxResult.success();
	}
	
	@PostMapping("/stop/{appid}")
	public AjaxResult stop(@PathVariable String appid) {
		// 获取open_app
		Entity openApp = Db.createSqlParser("open_app").findById(appid);
		if (openApp == null) {
			return AjaxResult.error("open_app不存在，id：" + appid);
		}
		
		// 停止
		try {
			cdcHelper.stop(appid);
		} catch (Exception e) {
            log.error("[cdc]停止任务失败: {}", e.getMessage(), e);
		}
		
		return AjaxResult.success();
	}
}
